/*
 * @Author: MrRice
 * @Date: 2024-12-18 11:43:46
 * @LastEditors: MrRice 1246333567@qq.com
 * @LastEditTime: 2024-12-18 16:41:40
 * @FilePath: \rotateBoundBoxApp\src\boundBox.js
 * @Description:
 * -----小舟从此逝，江海寄余生----
 * Copyright (c) 2024 by 米大饭, All Rights Reserved.
 */
import { Box3, Matrix4, Vector3 } from "three";

export const getBoundBox = (meshes, euler) => {
  let finalBox = new Box3();

  for (let s = 0; s < meshes.length; s++) {
    meshes[s].updateMatrixWorld(true); // 更新矩阵
    meshes[s].updateMatrix(); // 更新矩阵
    meshes[s].needsUpdate = true; // 标记需要更新
    let box = new Box3().setFromObject(meshes[s]);
    finalBox.union(box);
  }
  // return finalBox;

  const matrix = new Matrix4();
  const pos = finalBox.getCenter(new Vector3());
  matrix.makeTranslation(pos);
  matrix.multiply(new Matrix4().makeRotationFromEuler(euler));
  matrix.multiply(new Matrix4().makeTranslation(pos.clone().negate()));

  let box2 = new Box3();
  for (let s = 0; s < meshes.length; s++) {
    // meshes[s].applyMatrix4(matrix);

    let meshClone = meshes[s].clone();
    meshClone.matrix.copy(meshes[s].matrixWorld);
    meshClone.applyMatrix4(matrix);
    meshClone.updateMatrixWorld(true); // 更新矩阵
    meshClone.updateMatrix(); // 更新矩阵
    meshClone.needsUpdate = true; // 标记需要更新
    let boxIn = new Box3().setFromObject(meshClone);
    box2.union(boxIn);

    meshClone.geometry.dispose();
    meshClone.material.dispose();
    meshClone = null;
  }

  return box2;
};
